package com.example.wms;

import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.Toast;
import com.example.classes.*;

/**
 * Activity for managing the Login screen.
 */
public class LoginHandler extends Activity
{
    private DataBase db;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        db = new DataBase(this);
        db.open();

        Intent intent = getIntent();
        String username = intent.getStringExtra(StartupActivity.USER_ID);
        String password = intent.getStringExtra(StartupActivity.PASS);

        if (loginCheck(username, password))
        {
            db.close();
            Toast.makeText(LoginHandler.this, "Welcome, " + username + ".", Toast.LENGTH_LONG).show();
            Intent homeIntent = new Intent(this, HomeHandler.class);
            homeIntent.putExtra("username", username);
            homeIntent.putExtra("email", getEmail(username));
            startActivity(homeIntent);
        }
        finish();
    }

    /**
     * Authenticates the inputted credentials.
     * @param uname the username
     * @param upass the password
     */
    boolean loginCheck(String uname, String upass)
    {
        Member mb=null;
        try{
        mb = db.getEntry(uname);
        }
        catch(Exception a){
            Toast.makeText(LoginHandler.this," Database did not return valid value ",Toast.LENGTH_LONG).show();
        }
        if (mb == null)
        {
            Toast.makeText(LoginHandler.this, "u r suck h4k3r n00b", Toast.LENGTH_LONG).show();
            return false;
        }
        if (!mb.isLocked() && mb.getPassword().equals(Encryptor.encrypt(upass)))
        {
            mb.resetStrikes();
            db.update(mb);
            return true;
        }
        if (!uname.equals("admin"))
        {
            mb.incorrectLogin();
            db.update(mb);
        }
        if (mb.isLocked())
            Toast.makeText(LoginHandler.this, "This account has been locked!", Toast.LENGTH_LONG).show();
        else
            Toast.makeText(LoginHandler.this, "u r suck h4k3r n00b", Toast.LENGTH_LONG).show();
        return false;
    }

    /**
     * Gets the user's contact information.
     * @param uname the username
     * @return the email of the Member associated with the username
     */
    String getEmail(String uname)
    {
        Member mb =null;
        try{db.getEntry(uname);
        }
        catch (Exception e)
        {
            Log.d("WMS-DEBUG-LoginHANDLE",e.getMessage());
        }
        if (mb != null)
            return mb.getContact();
        return "No email listed.";
    }
}